package shutdown

import (
	"encoding/json"
	"io/ioutil"
	"strings"
)

var portPath = "config/port.json"

func SetPortPath(_file string) {
	portPath = _file
}

func GetPortByFilePath(projectDir, filePath string) (string, error) {
	var (
		err       error
		port      string
		fileBytes []byte
		portMap   map[string]CustomPort
	)

	if fileBytes, err = ioutil.ReadFile(projectDir + portPath); err == nil {
		if err = json.Unmarshal(fileBytes, &portMap); err == nil {
			for k, v := range portMap {
				if projectDir+v.BuildSource == filePath {
					port = k
					break
				}
			}
		}
	}
	return port, err
}

func GetPortInfoByFilePath(projectDir, filePath string) (CustomPort, error) {
	var (
		err       error
		port      CustomPort
		fileBytes []byte
		portMap   map[string]CustomPort
	)

	if fileBytes, err = ioutil.ReadFile(projectDir + portPath); err == nil {
		if err = json.Unmarshal(fileBytes, &portMap); err == nil {
			for k, v := range portMap {
				if projectDir+v.BuildSource == filePath {
					v.Port = k
					port = v
					break
				}
			}
		}
	}
	return port, err
}

func GetPortInfoByTag(projectDir, tag string) (CustomPort, error) {
	var (
		err       error
		port      CustomPort
		fileBytes []byte
		portMap   map[string]CustomPort
	)

	if fileBytes, err = ioutil.ReadFile(projectDir + portPath); err == nil {
		if err = json.Unmarshal(fileBytes, &portMap); err == nil {
			for k, v := range portMap {
				if checkContains(v.Tag, tag) {
					v.Port = k
					port = v
					break
				}
			}
		}
	}
	return port, err
}

func checkContains(str, substr string) bool {
	return strings.Contains(","+str+",", ","+substr+",")
}
